package com.sc.test.screeninfo;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.sc.test.R;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Shen Chao
 * Created by 2018-12-05
 */
public class ScreenInfoActivity extends AppCompatActivity {
    @BindView(R.id.tv_screen_info)
    TextView tvScreenInfo;
    StringBuffer sb = new StringBuffer();
    public static final String CHINA_MOVE_ONE = "46000";//中国移动
    public static final String CHINA_MOVE_TWO = "46002";
    public static final String CHINA_MOVE_THREE = "46007";
    public static final String CHINA_MOVE_FOUR = "46008";
    public static final String CHINA_UNICOM_ONE = "46001";//中国联通
    public static final String CHINA_UNICOM_TWO = "46006";//中国联通
    public static final String CHINA_UNICOM_THREE = "46009";//中国联通
    public static final String CHINA_TELECOM_ONE = "46003";//中国电信
    public static final String CHINA_TELECOM_TWO = "46005";//中国电信
    public static final String CHINA_TELECOM_THREE = "46011";//中国电信

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去掉title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getSupportActionBar().hide();
        //去掉状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_screen_info);
        ButterKnife.bind(this);

//        第一种方法：
//        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
//        DisplayMetrics metrics1 = new DisplayMetrics();
//        wm.getDefaultDisplay().getMetrics(metrics1);
//        第二种方法
//        DisplayMetrics metrics2 = new DisplayMetrics();
//        getWindowManager().getDefaultDisplay().getMetrics(metrics2);
//        第三种方法
//        DisplayMetric metrics3 = getResources().getDisplayMetric();

        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        float density = displayMetrics.density;
        float xdpi = displayMetrics.xdpi;
        float ydpi = displayMetrics.ydpi;
        int heightPixels = displayMetrics.heightPixels;
        int widthPixels = displayMetrics.widthPixels;
        int densityDpi = displayMetrics.densityDpi;

        sb.append("屏幕密度：" + densityDpi + ",   " + density);
        sb.append("\n");
        sb.append("屏幕宽：" + widthPixels + "px");
        sb.append("\n");
        sb.append("屏幕高：" + heightPixels + "px");
        sb.append("\n");
        sb.append("x轴密度：" + xdpi);
        sb.append("\n");
        sb.append("y轴密度：" + ydpi);
        sb.append("\n");
        String versionCode = getVersionCode();
        sb.append("APP版本代码：" + versionCode);
        sb.append("\n");
        String versionName = getVersionName();
        sb.append("APP版本号：" + versionName);
        sb.append("\n");
        String OSVersion = getOsVersion();
        sb.append("系统版本号：" + OSVersion);
        sb.append("\n");
        String deviceBrand = getDeviceBrand();
        sb.append("手机品牌：" + deviceBrand);
        sb.append("\n");
        String deviceType = getDeviceType();
        sb.append("手机型号：" + deviceType);
        sb.append("\n");
        String WifiMacAddress = getWifiMacAddress();
        sb.append("mac地址：" + WifiMacAddress);
        sb.append("\n");
        String ipAddressString = getIpAddressString();
        sb.append("ip地址：" + ipAddressString);
        sb.append("\n");
        String iMEI = getIMEI();
        sb.append("IMEI：" + iMEI);
        sb.append("\n");
        String carrier = getCarrier();
        sb.append("运营商：" + carrier);
        sb.append("\n");
        String netWorkType = getNetWorkType();
        sb.append("网络类型：" + netWorkType);
        sb.append("\n");
        boolean isRoot = isRoot();
        if (isRoot) {
            sb.append("是否root：是");
        } else {
            sb.append("是否root：否");
        }
        sb.append("\n");

        tvScreenInfo.setText(sb.toString());
    }

    private String getOsVersion() {
        return Build.VERSION.SDK + " " + Build.VERSION.RELEASE;
    }

    private String getVersionName() {
        PackageManager pm = this.getPackageManager();
        PackageInfo packageInfo = null;
        try {
            packageInfo = pm.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String versionName = packageInfo.versionName;
        return versionName;
    }

    private String getVersionCode() {
        PackageManager pm = getPackageManager();
        PackageInfo packageInfo = null;
        try {
            packageInfo = pm.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String versionCode = packageInfo.versionCode + "";
        return versionCode;

    }

    /**
     * 获取手机品牌
     *
     * @return
     */
    public String getDeviceBrand() {
        return Build.BRAND;
    }

    /**
     * 获取手机型号
     *
     * @return
     */
    public String getDeviceType() {
        return Build.MODEL;
    }

    /**
     * 获取mac地址
     *
     * @return
     */
    public String getWifiMacAddress() {
        try {
            String interfaceName = "wlan0";
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                if (!intf.getName().equalsIgnoreCase(interfaceName)) {
                    continue;
                }

                byte[] mac = intf.getHardwareAddress();
                if (mac == null) {
                    return "";
                }

                StringBuilder buf = new StringBuilder();
                for (byte aMac : mac) {
                    buf.append(String.format("%02X:", aMac));
                }
                if (buf.length() > 0) {
                    buf.deleteCharAt(buf.length() - 1);
                }
                return buf.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取ip地址
     *
     * @return
     */
    public String getIpAddressString() {
        try {
            for (Enumeration<NetworkInterface> enNetI = NetworkInterface
                    .getNetworkInterfaces(); enNetI.hasMoreElements(); ) {
                NetworkInterface netI = enNetI.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = netI
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取iemi
     *
     * @return
     */
    public String getIMEI() {
        String imei = "";
        TelephonyManager telephonyManager = ((TelephonyManager) getSystemService(TELEPHONY_SERVICE));
        final int READ_PHONE_STATE = 1;
        String[] PERMISSIONS_READ_PHONE_STATE = {"android.permission.READ_PHONE_STATE"};
        if (telephonyManager != null) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, PERMISSIONS_READ_PHONE_STATE, READ_PHONE_STATE);
            } else {
                imei = telephonyManager.getDeviceId();
            }
        }
        return imei;
    }

    /**
     * 获取运营商
     *
     * @return
     */
    public String getCarrier() {
        String res = "";
        TelephonyManager telManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        if (telManager != null) {
            String operator = telManager.getSimOperator();
            if (operator != null) {

                if (operator.equals(CHINA_MOVE_ONE) || operator.equals(CHINA_MOVE_TWO) || operator.equals(CHINA_MOVE_THREE) || operator.equals(CHINA_MOVE_FOUR)) {
                    //中国移动
                    res = "中国移动";
                } else if (operator.equals(CHINA_UNICOM_ONE) || operator.equals(CHINA_UNICOM_TWO) || operator.equals(CHINA_UNICOM_THREE)) {
                    //中国联通
                    res = "中国联通";
                } else if (operator.equals(CHINA_TELECOM_ONE) || operator.equals(CHINA_TELECOM_TWO) || operator.equals(CHINA_TELECOM_THREE)) {
                    //中国电信
                    res = "中国电信";
                }
            }
        }
        return res;
    }

    /**
     * 获取网络类型
     *
     * @return
     */
    public String getNetWorkType() {
        //获取系统的网络服务
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        //如果当前没有网络
        if (null == connManager)
            return "";

        //获取当前网络类型，如果为空，返回无网络
        NetworkInfo activeNetInfo = connManager.getActiveNetworkInfo();
        if (activeNetInfo == null || !activeNetInfo.isAvailable()) {
            return "";
        }

        // 判断是不是连接的是不是wifi
        NetworkInfo wifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (null != wifiInfo) {
            NetworkInfo.State state = wifiInfo.getState();
            if (null != state)
                if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
                    return "wifi";
                }
        }

        // 如果不是wifi，则判断当前连接的是运营商的哪种网络2g、3g、4g等
        NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if (null != networkInfo) {
            NetworkInfo.State state = networkInfo.getState();
            String strSubTypeName = networkInfo.getSubtypeName();
            if (null != state)
                if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
                    switch (activeNetInfo.getSubtype()) {
                        //如果是2g类型
                        case TelephonyManager.NETWORK_TYPE_GPRS: // 联通2g
                        case TelephonyManager.NETWORK_TYPE_CDMA: // 电信2g
                        case TelephonyManager.NETWORK_TYPE_EDGE: // 移动2g
                        case TelephonyManager.NETWORK_TYPE_1xRTT:
                        case TelephonyManager.NETWORK_TYPE_IDEN:
                            return "2g";
                        //如果是3g类型
                        case TelephonyManager.NETWORK_TYPE_EVDO_A: // 电信3g
                        case TelephonyManager.NETWORK_TYPE_UMTS:
                        case TelephonyManager.NETWORK_TYPE_EVDO_0:
                        case TelephonyManager.NETWORK_TYPE_HSDPA:
                        case TelephonyManager.NETWORK_TYPE_HSUPA:
                        case TelephonyManager.NETWORK_TYPE_HSPA:
                        case TelephonyManager.NETWORK_TYPE_EVDO_B:
                        case TelephonyManager.NETWORK_TYPE_EHRPD:
                        case TelephonyManager.NETWORK_TYPE_HSPAP:
                            return "3g";
                        //如果是4g类型
                        case TelephonyManager.NETWORK_TYPE_LTE:
                            return "4g";
                        default:
                            //中国移动 联通 电信 三种3G制式
                            if (strSubTypeName.equalsIgnoreCase("TD-SCDMA") || strSubTypeName.equalsIgnoreCase("WCDMA") || strSubTypeName.equalsIgnoreCase("CDMA2000")) {
                                return "3g";
                            } else {
                                return "mobile";
                            }
                    }
                }
            return "";
        }
        return "";
    }

    //判断手机是否root
    public boolean isRoot() {
        String binPath = "/system/bin/su";
        String xBinPath = "/system/xbin/su";

        if (new File(binPath).exists() && isCanExecute(binPath)) {
            return true;
        }
        if (new File(xBinPath).exists() && isCanExecute(xBinPath)) {
            return true;
        }
        return false;
    }

    private static boolean isCanExecute(String filePath) {
        java.lang.Process process = null;
        try {
            process = Runtime.getRuntime().exec("ls -l " + filePath);
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String str = in.readLine();
            if (str != null && str.length() >= 4) {
                char flag = str.charAt(3);
                if (flag == 's' || flag == 'x')
                    return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
        return false;
    }

//    private static final int READ_PHONE_STATE = 1;
//    private static String[] PERMISSIONS_READ_PHONE_STATE = {"android.permission.READ_PHONE_STATE"};
//
//    public void verifyStoragePermissions(Activity activity) {
//        try {
//            //检测是否有写的权限
//            int permission = ActivityCompat.checkSelfPermission(activity,"android.permission.READ_PHONE_STATE");
//            if (permission != PackageManager.PERMISSION_GRANTED) {
//                // 没有写的权限，去申请写的权限，会弹出对话框的
//                ActivityCompat.requestPermissions(activity, PERMISSIONS_READ_PHONE_STATE, READ_PHONE_STATE);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    public void openCarema(View view) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivity(intent);
    }

    public void openGPS(View view) {
        //获取用户手机的位置服务
        LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
        MyLocationListener locationListener = new MyLocationListener();
//        //查询条件
//        Criteria criteria = new Criteria();
//        //精确度   最高
//        criteria.setAccuracy(Criteria.ACCURACY_FINE);
//        //是否运行产生开销  默认为false
//        criteria.setCostAllowed(true);
//        //电量的消耗-高电量  默认为int mPowerRequirement = NO_REQUIREMENT //不做特殊处理
//        criteria.setPowerRequirement(Criteria.POWER_HIGH);
//        String provider = lm.getBestProvider(criteria, true);
//        System.out.println("位置提供者:" + provider);

        String[] PERMISSIONS_GPRS = {"android.permission.ACCESS_COARSE_LOCATION", "android.permission.ACCESS_FINE_LOCATION"};
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, PERMISSIONS_GPRS, 1);
        } else {
//            Location location = lm.getLastKnownLocation(provider);
            Location location = null;
            String providerResult = "";
            List<String> providers = lm.getProviders(true);
            for (String provider : providers) {
                Location l = lm.getLastKnownLocation(provider);
                if (l == null) {
                    continue;
                }
                if (location == null || l.getAccuracy() < location.getAccuracy()) {
                    location = l;
                    providerResult = provider;
                    System.out.println("定位方式:" + provider);
                }
            }


//                lm.requestLocationUpdates("gps", 60000, 1, locationListener);
            double longitude = location.getLongitude();
            double latitude = location.getLatitude();
            double accuracy = location.getAccuracy();
            String result = "经度:" + longitude + "\n" + "纬度:" + latitude + "\n精确度:" + accuracy + "m";
            System.out.println(result);
            lm.requestLocationUpdates(providerResult, 0, 0, locationListener);
        }
    }

    private class MyLocationListener implements LocationListener {

        //当位置发生变化的时候 调用.
        @Override
        public void onLocationChanged(Location location) {
            double longitude = location.getLongitude();
            double latitude = location.getLatitude();
            double accuracy = location.getAccuracy();
            String result = "经度:" + longitude + "\n" + "纬度:" + latitude + "\n精确度:" + accuracy + "m";
            TextView tv = new TextView(getApplicationContext());
            tv.setText(result);
            setContentView(tv);
        }

        //位置提供者状态变化的时候 调用
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        //当某个位置提供者 被启用
        @Override
        public void onProviderEnabled(String provider) {

        }

        //当某个位置提供者 被禁用
        @Override
        public void onProviderDisabled(String provider) {

        }

    }

}
